'use client'

import { useEffect, useRef, useState } from 'react'
import { useRouter } from 'next/navigation'
import Link from 'next/link'
import { LIVENESS_BASE_URL } from '@/lib/config'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { IconBuilding, IconCamera, IconUpload } from '@tabler/icons-react'

export default function FaceEnrollPage() {
  const router = useRouter()
  const videoRef = useRef<HTMLVideoElement>(null)
  const canvasRef = useRef<HTMLCanvasElement>(null)
  const [username, setUsername] = useState('')
  const [stream, setStream] = useState<MediaStream | null>(null)
  const [images, setImages] = useState<string[]>([])
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [error, setError] = useState('')
  const [success, setSuccess] = useState('')

  useEffect(() => {
    return () => {
      if (stream) stream.getTracks().forEach(t => t.stop())
    }
  }, [stream])

  const startCamera = async () => {
    try {
      const s = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'user', width: 640, height: 480 } })
      setStream(s)
      if (videoRef.current) videoRef.current.srcObject = s
    } catch (e) {
      setError('无法访问摄像头，请检查浏览器权限')
    }
  }

  const capture = () => {
    if (!videoRef.current || !canvasRef.current) return
    const v = videoRef.current
    const c = canvasRef.current
    const ctx = c.getContext('2d')
    if (!ctx) return
    c.width = v.videoWidth
    c.height = v.videoHeight
    ctx.drawImage(v, 0, 0)
    const data = c.toDataURL('image/jpeg', 0.9)
    setImages(prev => [...prev, data].slice(0, 5))
  }

  const onFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files
    if (!files) return
    const arr: string[] = []
    for (const f of Array.from(files).slice(0, 5)) {
      const buf = await f.arrayBuffer()
      const b64 = `data:${f.type};base64,${Buffer.from(buf).toString('base64')}`
      arr.push(b64)
    }
    setImages(prev => [...prev, ...arr].slice(0, 5))
  }

  // 将 dataURL 转换为 Blob
  const dataURLToBlob = (dataUrl: string) => {
    const arr = dataUrl.split(',')
    const mime = arr[0].match(/:(.*?);/)?.[1] || 'image/jpeg'
    const bstr = atob(arr[1] || '')
    let n = bstr.length
    const u8arr = new Uint8Array(n)
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n)
    }
    return new Blob([u8arr], { type: mime })
  }

  const submit = async () => {
    try {
      setIsSubmitting(true)
      setError('')
      setSuccess('')
      if (!username) { setError('请输入用户名'); return }
      if (images.length === 0) { setError('请至少上传或抓拍一张照片'); return }
<<<<<<< HEAD
      const endpoint = process.env.NEXT_PUBLIC_LIVENESS_API || ''
      if (!endpoint) { setError('未配置 NEXT_PUBLIC_LIVENESS_API，请在 h5/.env.local 设置'); return }
=======
      const endpoint = LIVENESS_BASE_URL
>>>>>>> 2b1414599d9e635ed6f7f739f5d192143c8f58df

      // 兼容你的后端：使用 /face/register，multipart 表单上传
      const url = `${endpoint}/register`
      const fd = new FormData()
      // 取第一张图做入库（如需多张可循环多次调用）
      const first = images[0]
      const blob = dataURLToBlob(first)
      fd.append('image', blob, `${username}.jpg`)
      fd.append('person_name', username)
      fd.append('person_id', username)

      const res = await fetch(url, { method: 'POST', body: fd })
      if (!res.ok) {
        let msg = ''
        try { msg = (await res.text())?.slice(0, 400) || '' } catch {}
        throw new Error(`录入服务返回异常 (${res.status}) ${msg}`)
      }
      let data: any = {}
      try { data = await res.json() } catch {}
      if (data?.success !== false) {
        setSuccess('录入成功！现在可以返回登录进行验证')
        setTimeout(() => router.push('/login'), 1200)
      } else {
        setError(data?.message || '录入失败，请重试')
      }
    } catch (e: any) {
      setError(e?.message || '录入失败，请检查后端服务')
    } finally {
      setIsSubmitting(false)
    }
  }

  return (
    <div className="min-h-screen gradient-bg flex items-center justify-center p-4">
      <div className="w-full max-w-3xl">
        <div className="text-center mb-8">
          <div className="flex items-center justify-center gap-3 mb-4">
            <div className="w-16 h-16 bg-blue-100 rounded-xl flex items-center justify-center shadow-lg">
              <IconBuilding className="w-8 h-8 text-blue-600" />
            </div>
            <div className="text-left">
              <h1 className="text-2xl font-bold text-gray-900 dark:text-gray-100">人脸底库录入</h1>
              <p className="text-sm text-gray-600 dark:text-gray-400">Face Enrollment</p>
            </div>
          </div>
        </div>

        <Card className="glass-effect border border-white/20 dark:border-gray-700/20 shadow-xl">
          <CardHeader className="text-center pb-4">
            <CardTitle className="text-xl font-semibold text-gray-900 dark:text-gray-100">录入您的人脸用于管理员验证</CardTitle>
            <CardDescription className="text-gray-600 dark:text-gray-400">支持摄像头抓拍或上传图片，最多5张</CardDescription>
          </CardHeader>
          <CardContent className="space-y-6">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div className="space-y-4">
                <Label className="text-sm text-gray-700 dark:text-gray-300">用户名</Label>
                <Input value={username} onChange={e => setUsername(e.target.value)} placeholder="请输入用户名" autoComplete="username" />

                <div className="space-y-2">
                  <div className="flex items-center justify-between">
                    <Label className="text-sm text-gray-700 dark:text-gray-300">摄像头</Label>
                    <div className="flex gap-2">
                      <Button variant="outline" onClick={startCamera} className="px-3"><IconCamera className="w-4 h-4 mr-1" />启动</Button>
                      <Button variant="outline" onClick={capture} className="px-3" disabled={!stream}><IconCamera className="w-4 h-4 mr-1" />抓拍</Button>
                    </div>
                  </div>
                  <div className="relative bg-gray-100 dark:bg-gray-800 rounded-lg overflow-hidden">
                    <video ref={videoRef} autoPlay playsInline muted className="w-full h-64 object-cover" />
                    <canvas ref={canvasRef} className="hidden" />
                  </div>
                </div>
              </div>

              <div className="space-y-4">
                <Label className="text-sm text-gray-700 dark:text-gray-300">图片上传</Label>
                <div className="flex items-center gap-3">
                  <Input type="file" accept="image/*" multiple onChange={onFileChange} />
                  <Button variant="outline" onClick={() => setImages([])} className="px-3">清空</Button>
                </div>
                <div className="grid grid-cols-3 gap-3">
                  {images.map((src, i) => (
                    <img key={i} src={src} alt={`shot-${i}`} className="w-full h-24 object-cover rounded-lg border border-white/20" />
                  ))}
                </div>
              </div>
            </div>

            {error && (
              <Alert variant="destructive" className="border-red-200 bg-red-50 dark:bg-red-900/20">
                <AlertDescription className="text-red-700 dark:text-red-300">{error}</AlertDescription>
              </Alert>
            )}
            {success && (
              <Alert className="border-green-200 bg-green-50 dark:bg-green-900/20">
                <AlertDescription className="text-green-700 dark:text-green-300">{success}</AlertDescription>
              </Alert>
            )}

            <div className="flex items-center justify-between">
              <Link href="/login" className="text-sm text-blue-600 hover:underline">返回登录</Link>
              <Button onClick={submit} disabled={isSubmitting} className="bg-gradient-to-r from-blue-600 to-blue-700 text-white">
                {isSubmitting ? (
                  <div className="flex items-center gap-2"><div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"></div> 提交中…</div>
                ) : (
                  <div className="flex items-center gap-2"><IconUpload className="w-4 h-4" /> 提交录入</div>
                )}
              </Button>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  )
}
